<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="类型名称">
          <el-input v-model="searchData.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item prop="code" label="类型编码">
          <el-input v-model="searchData.code" placeholder="请输入类型编码" />
        </el-form-item>
        <el-form-item prop="userType" label="适用用户类型">
          <el-select v-model="searchData.userType" placeholder="请选择" clearable style="width: 150px;">
            <el-option label="顾客" :value="1" />
            <el-option label="商户" :value="2" />
            <el-option label="配送员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增反馈类型</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="getFeedbackTypeData">刷新数据</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="feedbackTypeData">
          <el-table-column type="index" width="80" align="center" label="序号" :index="indexMethod" />
          <el-table-column prop="name" label="类型名称" align="center" width="150" />
          <el-table-column prop="code" label="类型编码" align="center" width="150" />
          <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip width="200" />
          <el-table-column prop="userTypeName" label="适用用户类型" align="center" width="150">
            <template #default="scope">
              <el-tag :type="getUserTypeTagType(scope.row.userType)">{{ scope.row.userTypeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sortOrder" label="排序序号" align="center" width="100" />
          <el-table-column prop="statusName" label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.statusName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column prop="updateTime" label="更新时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="danger" text bg size="small" @click="deleteFeedbackType(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑反馈类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isUpdate ? '编辑反馈类型' : '新增反馈类型'"
      width="600px"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入类型编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="适用用户类型" prop="userType">
          <el-select v-model="formData.userType" placeholder="请选择适用用户类型" style="width: 100%;">
            <el-option label="顾客" :value="1" />
            <el-option label="商户" :value="2" />
            <el-option label="配送员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="999" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  getFeedbackTypeListApi,
  createFeedbackTypeApi,
  updateFeedbackTypeApi,
  deleteFeedbackTypeApi
} from "@/api/feedback-manage"
import { type FeedbackTypeData, type FeedbackTypeFormData } from "@/api/feedback-manage/types/feedback-type"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  name: "FeedbackTypeManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 查询
const feedbackTypeData = ref<FeedbackTypeData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  code: "",
  userType: undefined as number | undefined,
  status: undefined as number | undefined
})

const getFeedbackTypeData = () => {
  loading.value = true
  getFeedbackTypeListApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    code: searchData.code || undefined,
    userType: searchData.userType || undefined,
    status: searchData.status
  })
    .then(({ data }) => {
      paginationData.total = data.total
      feedbackTypeData.value = data.list
    })
    .catch(() => {
      feedbackTypeData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage = 1
  getFeedbackTypeData()
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

//#region 新增/编辑
const DEFAULT_FORM_DATA: FeedbackTypeFormData = {
  name: "",
  code: "",
  description: "",
  userType: 1,
  sortOrder: 0,
  status: 1
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<FeedbackTypeFormData>(cloneDeep(DEFAULT_FORM_DATA))
const isUpdate = ref<boolean>(false)

const formRules: FormRules<FeedbackTypeFormData> = {
  name: [{ required: true, trigger: "blur", message: "请输入类型名称" }],
  code: [
    { required: true, trigger: "blur", message: "请输入类型编码" },
    { pattern: /^[a-zA-Z0-9_]+$/, trigger: "blur", message: "编码只能包含字母、数字和下划线" }
  ],
  userType: [{ required: true, trigger: "change", message: "请选择适用用户类型" }],
  sortOrder: [{ required: true, trigger: "blur", message: "请输入排序序号" }],
  status: [{ required: true, trigger: "change", message: "请选择状态" }]
}

const handleCreate = () => {
  dialogVisible.value = true
  isUpdate.value = false
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const handleUpdate = (row: FeedbackTypeData) => {
  dialogVisible.value = true
  isUpdate.value = true
  formData.value = {
    id: row.id,
    name: row.name,
    code: row.code,
    description: row.description,
    userType: row.userType,
    sortOrder: row.sortOrder,
    status: row.status
  }
}

const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = isUpdate.value ? updateFeedbackTypeApi : createFeedbackTypeApi
    api(formData.value)
      .then(() => {
        ElMessage.success(isUpdate.value ? "修改成功" : "创建成功")
        dialogVisible.value = false
        getFeedbackTypeData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

//#region 删除
const deleteFeedbackType = (row: FeedbackTypeData) => {
  ElMessageBox.confirm(`确认删除反馈类型"${row.name}"?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteFeedbackTypeApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getFeedbackTypeData()
    })
  })
}

//#region 工具函数
const getUserTypeTagType = (userType: number) => {
  switch (userType) {
    case 1:
      return "success"
    case 2:
      return "warning"
    case 3:
      return "info"
    default:
      return "info"
  }
}

const indexMethod = (index: number) => {
  return index + 1 + (paginationData.currentPage - 1) * paginationData.pageSize
}

//#region 监听分页参数变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getFeedbackTypeData, { immediate: true })
</script>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>